<!--
/**
* @author xuyh0817
* @email xuyh0817@foxmail.com
* @date 2022-02-22 01:23
* @version 2.0.0
* @doc todo
* @website todo
* @remark  如果要分发源码，需在本文件顶部保留此文件头信息！！
*/
-->
<template>
  <a-modal
      title="批量添加表单项"
      :visible="visible"
      :footer="null"
      centered
      :mask-closable="false"
      destroy-on-close
      width="50%"
      @cancel="$emit('update:visible',false)"
  >
    <div class="x-render-code">
      <a-radio-group v-model="addType" style="margin-bottom: 20px;">
        <a-radio value="item">逐个添加</a-radio>
        <a-radio value="db">数据库文件导入[MYSQL]</a-radio>
      </a-radio-group>

      <a-row v-for="(item,index) in formItems" :key="index" :gutter="[8,8]">
        <a-col span="8">
          <div
              style="width: 100%;padding: 2px;"
              :class="fieldCountObj[item.prop] > 1 || !item.prop ? 'form-item-error':'' "
          >
            <a-input
                :value="item.prop"
                placeholder="请输入prop"
                allow-clear
                type="text"
                @change="changeHandler($event,index,'prop')"
            />
          </div>
        </a-col>
        <a-col span="8">
          <a-input
              :value="item.label"
              placeholder="请输入label"
              allow-clear
              type="text"
              @change="changeHandler($event,index,'label')"
          />
        </a-col>
        <a-col span="8">
          <div style="display: flex;flex-flow: row nowrap;">
            <a-select
                show-search
                style="width: 80%"
                :value="item.type"
                @change="changeHandler($event,index,'type')"
            >
              <a-select-option
                  v-for="(ite,ind) in xDesignForm.sortedComps"
                  :key="ite.type + '-' + index +'-' + ind"
                  :value="ite.type"
              >
                {{ ite.type }} - {{ ite.formItem.label }}
              </a-select-option>
            </a-select>
            <div class="x-render-icon-container">
              <a-icon
                  v-if="formItems.length !== 1"
                  :style="{ fontSize: '24px' }"
                  type="minus-circle"
                  @click="removeHandler(index)"
              />
              <a-icon
                  v-if="formItems.length - 1 === index"
                  :style="{ fontSize: '24px' }"
                  type="plus-circle"
                  @click="addHandler"
              />
            </div>
          </div>
        </a-col>
      </a-row>
      <div v-show="addType === 'db'">
        <a-textarea v-model="sql" allow-clear placeholder="请输入数据结构" :rows="4"/>
      </div>
      <a-row :gutter="[20,10]">
        <a-col span="24">
          <p style="color: #f44;line-height: 24px;" v-html="errorTip"/>
        </a-col>
        <a-col span="24" style="text-align: center;">
          <a-button v-show="addType === 'db'" type="primary" style="margin: 0 8px;" @click="mysqlImportHandler">导入
          </a-button>
          <a-button type="primary" @click="addFormItemHandler">提交</a-button>
        </a-col>
      </a-row>
    </div>
  </a-modal>
</template>

<script>
import {assign, countBy} from 'lodash'

export default {
  name:'XRenderPreviewDialog',
  inject: ['xDesignForm'],
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      sql: 'CREATE TABLE `test` (\n' +
          "  `id` int NOT NULL AUTO_INCREMENT COMMENT '主键id',\n" +
          "  `create_user` int DEFAULT NULL COMMENT '创建人',\n" +
          "  `create_time` timestamp NULL DEFAULT NULL COMMENT '创建时间',\n" +
          "  `update_user` int DEFAULT NULL COMMENT '更新人',\n" +
          "  `update_time` timestamp NULL DEFAULT NULL COMMENT '更新时间',\n" +
          "  `remarks` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '备注',\n" +
          "  `deleted` tinyint(1) NOT NULL DEFAULT '0' COMMENT '删除标志，默认为0;0:未删除;1:已删除',\n" +
          "  `code` int DEFAULT NULL COMMENT '编号',\n" +
          "  `name` varchar(200) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL COMMENT '名称',\n" +
          "  `no` varchar(10) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL COMMENT '序号',\n" +
          "  `level` varchar(20) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL COMMENT '层级',\n" +
          "  `status` varchar(2) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL COMMENT '状态',\n" +
          '  PRIMARY KEY (`id`)\n' +
          ') ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;',
      addType: 'item',
      formItems: []
    }
  },
  computed: {
    // 字段出现的次数
    fieldCountObj: {
      get() {
        const {xDesignForm, formItems} = this
        // const formOptionsCount = countBy(xDesignForm.formOptions, ({formItem}) => String(formItem.prop).trim())
        // const formItemsCount = countBy(formItems, ({prop}) => String(prop).trim())
        // const assignObj = assign({}, formOptionsCount, formItemsCount)
        // for (const key in assignObj) {
        //   assignObj[key] = (formOptionsCount[key] ? formOptionsCount[key] : 0) + (formItemsCount[key] ? formItemsCount[key] : 0)
        // }
        // return assignObj
        return {}
      }
    },
    errorTip: {
      get() {
        const countObj = this.fieldCountObj
        let emptyKey = false
        const countMessage = []
        for (const key in countObj) {
          if (!key) {
            emptyKey = true
          }
          if (!!key && countObj[key] > 1) {
            countMessage.push(key)
          }
        }
        let message = ''
        if (emptyKey) {
          message = 'prop存在空值,请填写！<br/>'
        }
        if (countMessage.length > 0) {
          message += '属性存在多个：' + countMessage.join(',')
        }

        return message ? '注意: <br/>' + message : message
      }
    }
  },
  watch: {
    visible: {
      immediate: true,
      handler(val) {
        if (val) {
          const formItems = []
          formItems.push(
              {
                prop: Date.now() + '',
                label: '',
                type: this.xDesignForm.sortedComps[0]['type']
              }
          )
          this.formItems.splice(0, this.formItems.length, ...formItems)
        }
      }
    }
  },
  methods: {
    mysqlImportHandler() {
      let s = this.sql
      s = s.substring(s.indexOf('(') + 1, s.lastIndexOf(')'))
      s = s.replaceAll(/AUTO_INCREMENT|DECIMAL|DOUBLE|FLOAT|CLOB|BLOD|TEXT|tiny|int|timestamp|varchar|PRIMARY KEY|DEFAULT|\'\w+\'|COMMENT|\(\w+\)|[\(\)]|NOT NULL|NULL|CHARSET=\w+|COLLATE| CHARACTER SET|COLLATE utf8_bin|\(\d+\)|utf8_\w+|utf8|(ENGINE=)\w+/ig, '')
      s = s.replaceAll(/\`|\'/g, '')
      const split = s.split(',')
      const props = []
      for (let str of split) {
        str = str.trim()
        const split1 = str.split(' ')
        const prop = split1[0].trim()
        if (!props.includes(prop)) {
          props.push(prop)
          const label = split1.slice(1).join('')
          this.addFormItem(prop, label)
        }
      }
    },
    addFormItemHandler() {
      if (this.errorTip) {
        this.$message.error('请修改错误内容')
        return
      }
      const {formItems, xDesignForm} = this
      for (const formItem of formItems) {
        const type = formItem.type
        const prop = formItem.prop
        const label = formItem.label
        for (const comp of xDesignForm.sortedComps) {
          if (comp.type === type && !!prop) {
            const cloneComp = _.cloneDeep(comp)
            cloneComp.formItem.prop = prop
            cloneComp.formItem.label = label
            xDesignForm.formOptions.push(cloneComp)
          }
        }
      }
      this.$message.success('添加成功')
      this.$emit('update:visible', false)
    },
    addHandler() {
      this.addFormItem()
    },
    addFormItem(prop = Date.now() + '', label = '') {
      this.formItems.push(
          {
            prop: prop,
            label: label,
            type: this.xDesignForm.sortedComps[0]['type']
          }
      )
    },
    removeHandler(index) {
      this.formItems.splice(index, 1)
    },
    changeHandler(event, index, prop) {
      const value = prop !== 'type' ? event.target.value : event
      this.$set(this.formItems[index], prop, value)
    }
  }
}
</script>
<style lang="css" scoped>
.x-render-code {
  width: 100%;
  max-height: calc(80vh - 50px);
  overflow-y: auto;
  overflow-x: hidden;
}

.x-render-icon-container {
  width: 20%;
  padding: 0 5px;
  display: flex;
  flex-flow: row nowrap;
  justify-content: space-between;
  align-content: center;
  align-items: center;
}

.form-item-error {
  border: 1px #f44 dashed;
  border-radius: 5px;
}
</style>
